package cn.gcjxsc.controller.api.merchant;

import cn.gcjxsc.common.data.query.merchant.RechargeRecordQuery;
import cn.gcjxsc.common.data.vo.RechargeRecordVo;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.merchant.recharge.RechargeRecord;
import cn.gcjxsc.service.mall.OrderService;
import cn.gcjxsc.service.merchant.recharge.RechargeOrderService;
import cn.gcjxsc.service.merchant.recharge.RechargeRecordService;
import com.zgxl.common.vo.PageDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pumbaa
 * @since 1.0
 */
@RestController("apiMerchantRechargeController")
@RequestMapping("/api/merchant/recharge")
public class RechargeController {
    @Autowired
    private RechargeRecordService recordService;
    @Autowired
    private RechargeOrderService rechargeOrderService;
    @Autowired
    private OrderService orderService;

    /**
     * 查询商户充值记录
     */
    @RequestMapping("/list")
    public PageDataVo<RechargeRecordVo> queryRechargeRecord(RechargeRecordQuery filter,
                                                            @RequestParam(value = "page", defaultValue = "1", required = false) int page,
                                                            @RequestParam(value = "pageSize", defaultValue = "30", required = false) int pageSize) {
        filter.format();
        Page<RechargeRecord> list = recordService.findList(filter, page, pageSize);
        List<RechargeRecord> records = list.getContent();
        List<RechargeRecordVo> voList = new ArrayList<>();
        for (RechargeRecord record : records) {
            voList.add(recordService.converter(record, RechargeRecordVo.class));
        }

        PageDataVo<RechargeRecordVo> pageDataVo = new PageDataVo<>();
        pageDataVo.setList(voList);
        pageDataVo.setPageSize(pageSize);
        pageDataVo.setPageSize(page);
        pageDataVo.setTotal(list.getTotalElements());

        return pageDataVo;
    }

    /**
     * 生成订单
     * @param id 商户id
     * @param amount 金额
     * @return
     */
    @RequestMapping("/create")
    public String createRechargeOrder(@RequestParam("id") Integer id,
                                      @RequestParam("amount") BigDecimal amount) {
        BaseOrder order = rechargeOrderService.createRecharge(id, amount);

        try {
            order = orderService.saveOrUpdate(order);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return order.getSn();
    }
}
